package com.mx.tool.form.window.encryption;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.Digester;
import com.mx.tool.enums.HashEnum;
import com.mx.tool.util.NotifyUtil;

import javax.swing.*;
import java.util.Locale;

/**
 * @Author: 徐建鹏.
 * @create: 2021-11-10 07:32
 * @Description:
 */
public class HashWindow {
    private JPanel panel;
    private JTextArea contentArea;
    private JTextArea showArea;
    private JButton md5Button;
    private JButton sha384Button;
    private JButton sha512Button;
    private JButton sha1Button;
    private JButton sha256Button;
    private JCheckBox caseCheckBox;
    private JButton clearButton;


    public HashWindow() {
        md5Button.addActionListener(e -> hash(HashEnum.MD5));
        sha384Button.addActionListener(e -> hash(HashEnum.SHA384));
        sha512Button.addActionListener(e -> hash(HashEnum.SHA512));
        sha1Button.addActionListener(e -> hash(HashEnum.SHA1));
        sha256Button.addActionListener(e -> hash(HashEnum.SHA256));
        clearButton.addActionListener(e -> {
            contentArea.setText("");
            showArea.setText("");
        });
    }

    private void hash(HashEnum hashEnum){
        String content = contentArea.getText();
        String hash = "";
        switch (hashEnum){
            case MD5:
                hash = SecureUtil.md5(content);
                break;
            case SHA384:
                hash = new Digester(DigestAlgorithm.SHA384).digestHex(content);
                break;
            case SHA1:
                hash = SecureUtil.sha1(content);
                break;
            case SHA256:
                hash = SecureUtil.sha256(content);
                break;
            case SHA512:
                hash = new Digester(DigestAlgorithm.SHA512).digestHex(content);
                break;
            default:
                NotifyUtil.error("请选择正确的hash类型");
                break;
        }
        if(caseCheckBox.isSelected()){
            hash = hash.toUpperCase(Locale.ROOT);
        }
        showArea.setText(hash);
    }

    public JPanel getContent() {
        return panel;
    }
}
